package org.listbeast.core.playlist;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.listbeast.core.dataobjects.DiskSong;
import org.listbeast.core.dataobjects.SongCollection;

public class PlaylistHandler {

	private static final Logger LOG = Logger.getLogger(PlaylistHandler.class);

	final private String targetPath;

	public PlaylistHandler(String targetPath) {
		this.targetPath = targetPath;
	}

	public void createPlaylists(SongCollection<DiskSong> foundDiskSongs, boolean multiplePlaylists) {

		if (multiplePlaylists) { // create a playlist for every artist
			for (String artistName : foundDiskSongs.getArtistNames()) {
				createM3UPlaylist(artistName, foundDiskSongs.getArtistSongs(artistName));
			}
		} else { // create single playlist
			createM3UPlaylist("yourPlaylist", foundDiskSongs.getAllSongs());
		}

	}

	private void createM3UPlaylist(String fileName, Collection<DiskSong> artistSongs) {

		PrintWriter fstream = null;

		File playlist = new File(targetPath + "/" + fileName + ".m3u");

		if ((artistSongs != null) && (!artistSongs.isEmpty())) {

			try {

				fstream = new PrintWriter(new FileWriter(playlist));

				LOG.info("Creating playlist :" + playlist);

				for (DiskSong diskSong : artistSongs) {
					LOG.debug("Writing file :" + diskSong.getFilePath());
					fstream.println(diskSong.getFilePath());
				}

				LOG.info("Done");

			} catch (IOException e) {
				LOG.error(e);
			} finally {
				fstream.close();
			}
		}
	}

	public void copySongs(SongCollection<DiskSong> foundDiskSongs) {
		for (DiskSong diskSong : foundDiskSongs.getAllSongs()) {
			File srcFile = new File(diskSong.getFilePath());
			File destDir = new File(targetPath);

			try {
				FileUtils.copyFileToDirectory(srcFile, destDir);
				LOG.info("Copying file " + srcFile + " into directory "
						+ destDir + " ...");
			} catch (IOException e) {
				LOG.error(e);
			}
		}
	}
}
